package me.mouse.gokistats.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;

import me.mouse.gokistats.GokiStats;
import me.mouse.gokistats.talent.RegisterTalent;
import me.mouse.gokistats.talent.Talent;

public class PlayerData {
	private File file;
	private FileConfiguration config;

	private FileConfiguration load(File file) {
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileConfiguration config = YamlConfiguration.loadConfiguration(file);
		List<Talent> talent = RegisterTalent.getRegisterTalent();
		for (Talent t : talent) {
			int level = config.getInt(t.getName(), -1);
			if (level <= -1) {
				config.set(t.getName(), Integer.valueOf(0));
			}
		}
		int point = config.getInt("point", -1);
		if (point <= -1)
			config.set("point", Integer.valueOf(0));
		try {
			config.save(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return config;
	}

	public PlayerData(Player player) {
		this.file = new File(GokiStats.file, "player/" + player.getName() + ".yml");
		load(player.getName());
	}

	public PlayerData(OfflinePlayer player) {
		this.file = new File(GokiStats.file, "player/" + player.getName() + ".yml");
		load(player.getName());
	}

	public PlayerData(String player) {
		this.file = new File(GokiStats.file, "player/" + player + ".yml");
		load(player);
	}

	public PlayerData(File file) {
		this.file = file;
		this.config = load(file);
	}

	public void load(String player) {
		this.config = load(this.file);
		if (this.config != null)
			try {
				this.config.save(this.file);
				this.config = load(this.file);
				return;
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
	}

	public void save() {
		try {
			this.config.save(this.file);
			return;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public FileConfiguration getFileConfiguration() {
		return this.config;
	}

	public void setFileConfiguration(FileConfiguration config) {
		this.config = config;
	}

	public File getFile() {
		return this.file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public void clearTalent() {
		List<Talent> talent = RegisterTalent.getRegisterTalent();
		for (Talent t : talent)
			this.config.set(t.getName(), Integer.valueOf(0));
	}
}
